package com.statistics.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.statistics.dao.BasicDataDAO;
import com.statistics.dbutils.DBUtils;
import com.statistics.vo.BasicData;

public class BasicDataDAOImpl implements BasicDataDAO {
	private Connection conn = null ;
	private PreparedStatement pstmt = null ;
	private ResultSet rs = null ;
	private BasicData data = null ; 
	
	public BasicDataDAOImpl() {
		try {
			this.conn = DBUtils.getConnection() ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<BasicData> findAllData(int page) {
		int end = page * 50 ;
		int begin = end - 50 ;
		
		List<BasicData> all = new ArrayList<BasicData>();
		
		try {
			String sql = "select playerID,level,country,sex,experience,(select lvlUpExp from level_info where player.level = level_info.level) as lvlIpExp,"
					+ "onlineTime,(select count(*) from login_history where player.playerID = login_history.playerID)as loginCount," 
					+ "(SELECT count(*) FROM record_player_death where player.playerID = record_player_death.playerID) as deathCount"
					+ " from player limit " + begin + "," + end;
			
			this.pstmt = conn.prepareStatement(sql) ;
			this.rs = this.pstmt.executeQuery() ;
			while(rs.next()) {
				data = new BasicData() ;
				data.setPlayerID(rs.getInt(1)) ;
				data.setLevel(rs.getInt(2)) ;
				data.setCountry(rs.getInt(3)) ;
				data.setSex(rs.getInt(4)) ;
				data.setExperience(rs.getInt(5)) ;
				data.setLvlIpExp(rs.getInt(6)) ;
				data.setLoginCount(rs.getInt(7)) ;
				data.setDeathCount(rs.getInt(8)) ;
				all.add(data) ;
			}
		} catch (Exception e) {
			e.printStackTrace() ;
		} finally {
			DBUtils.close(conn) ;
			DBUtils.close(rs) ;
		}
		
		return all;
	}

}
